#include <iostream>
#include <unistd.h>
#include <semaphore.h>
#include <vector>
#include "LockGuard.hpp"

const int defaultSize = 5;
template <class T>
class RingQueue
{
private:
    void P(sem_t& sem)
    {
        sem_wait(&sem);
    }
    void V(sem_t& sem)
    {
        sem_post(&sem);
    }
public:
    RingQueue(int size = defaultSize)
    :_size(size), _c_step(0), _p_step(0), _ringqueue(size) //妈的，构造列表不能用已经定义过的属性，要用函数参数！！！！因为构造列表初始化的顺序是不固定的！！！
    {
        sem_init(&_space_sem, 0, _size);
        sem_init(&_data_sem, 0, 0);

        pthread_mutex_init(&_p_mutex, nullptr);
        pthread_mutex_init(&_c_mutex, nullptr);
    }

    void Push(const T& t)
    {
        P(_space_sem);
        {
            LockGuard lockguard(&_p_mutex);
            _ringqueue[_p_step] = t;
            _p_step ++;
            _p_step %= _size;
        }
        V(_data_sem);
    }

    void Pop(T* t)
    {
        P(_data_sem);
        {
            LockGuard lockguard(&_c_mutex);
            *t = _ringqueue[_c_step];
            _c_step ++;
            _c_step %= _size;
        }
        V(_space_sem);
        
    }
    ~RingQueue()
    {
        sem_destroy(&_space_sem);
        sem_destroy(&_data_sem);

        pthread_mutex_destroy(&_p_mutex);
        pthread_mutex_destroy(&_c_mutex);
    }
private:
    std::vector<T> _ringqueue;
    int _size;

    sem_t _space_sem;
    sem_t _data_sem;

    int _c_step;
    int _p_step;

    pthread_mutex_t _p_mutex;
    pthread_mutex_t _c_mutex;
};